//
//  LabelSizeUtil.m
//  Venue_reservation
//
//  Created by 蔡舟 on 15/8/31.
//  Copyright (c) 2015年 com.zkingsoft. All rights reserved.
//

#import "LabelSizeUtil.h"
#import <CoreText/CoreText.h>

@implementation LabelSizeUtil

#pragma mark 根据内容动态获取label的宽度   content:内容    size:字体大小    height:内容的高度（若不限制高度，可以设置为MAXFLOAT）  width:可显示内容的宽度（若不限制宽度度，可以设置为MAXFLOAT）
+(CGSize) labelSize:(NSString*)content andFontSize:(CGFloat) size andDefaultHeight:(CGFloat)height andDefaultWidth:(CGFloat) width{
    UIFont *fontSize = [UIFont systemFontOfSize:size];
    NSDictionary *dicFont = @{NSFontAttributeName:fontSize};
    CGSize labelSize = [content boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:dicFont context:nil].size;
    return  labelSize;
}


+(NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label
{
    NSString *text = [label text];
    UIFont   *font = [label font];
    CGRect    rect = [label frame];
    
    
    CTFontRef myFont = CTFontCreateWithName((CFStringRef)font.fontName,
                                            font.pointSize,
                                            NULL);
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
    
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    
    for (id line in lines)
    {
        CTLineRef lineRef = (__bridge CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        
        NSString *lineString = [text substringWithRange:range];
        [linesArray addObject:lineString];
    }
    
    return (NSArray *)linesArray;
}

@end
